<template>
  <div class="monitor-container">
    <div class="tab-bar">
      <CustomTabs :tabList="tabList" :activeName="activeName" @tabSelect="handelTabSelected" />
    </div>
    <div class="flex-center table-top">
      <div class="monitor-tab">
        <div
          v-for="item in monitorTypeList"
          :key="item.value"
          :class="['monitor-tab-item', { 'active-monitor-tab': monitorType === item.value }]"
          @click="changeMonitorType(item.value)"
        >
          {{ item.name }}
        </div>
      </div>
      <px-form ref="formRef" :model="queryParams" :inline="true" class="custom-form-ui search-form">
        <px-form-item label="监控周期" prop="cycle">
          <px-select v-model="queryParams.cycle" placeholder="请选择监控周期" clearable>
            <px-option v-for="item in cycleList" :key="item.value" :label="item.name" :value="item.value" />
          </px-select>
        </px-form-item>
        <!-- <px-form-item label="能源" prop="energy">
          <px-select v-model="queryParams.energy" placeholder="请选择能源" clearable>
            <px-option v-for="item in energyList" :key="item.value" :label="item.name" :value="item.value" />
          </px-select>
        </px-form-item> -->
        <px-form-item label="日期" prop="date">
          <px-date-picker
            v-model="queryParams.date"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </px-form-item>
        <div class="search-form-btn">
          <px-button type="primary" @click="handleQuery">查询</px-button>
          <px-button @click="resetQuery">重置</px-button>
        </div>
      </px-form>
    </div>
    <div v-loading="tableLoading" class="table-content">
      <px-table height="calc(100vh - 370px)" :data="tableData" size="small" border class="common-table">
        <px-table-column type="index" label="序号" fixed width="55" align="center" />
        <px-table-column prop="monitorTypeName" label="监控类型" min-width="120" show-overflow-tooltip />
        <px-table-column prop="spcConfigName" label="报警项" min-width="120" show-overflow-tooltip />
        <!-- <px-table-column prop="energyTypeName" label="能源类型" min-width="120" show-overflow-tooltip />
        <px-table-column prop="energyName" label="能源" min-width="120" show-overflow-tooltip /> -->
        <px-table-column prop="period" label="监控周期" min-width="120" show-overflow-tooltip>
          <template #default="scope">
            {{ formatPeriod(scope.row.period) }}
          </template>
        </px-table-column>
        <px-table-column prop="alarmTime" label="报警时间" min-width="120" show-overflow-tooltip />
        <px-table-column prop="alarmLevel" label="报警等级" min-width="120" show-overflow-tooltip align="center">
          <template #default="scope">
            <span v-if="scope.row.alarmLevel === null">""</span>
            <px-tag v-else :type="scope.row.alarmLevel === 'S' ? 'warning' : 'danger'">{{ formatAlarm(scope.row.alarmLevel) }}</px-tag>
          </template>
        </px-table-column>
        <px-table-column prop="alarmValue" label="报警值" min-width="120" show-overflow-tooltip />
        <px-table-column prop="spcThreshold" label="厂务内控值" min-width="120" show-overflow-tooltip />
        <px-table-column prop="hseThreshold" label="HSE管控值" min-width="120" show-overflow-tooltip />
        <px-table-column prop="eventType" label="状态" min-width="120" show-overflow-tooltip>
          <template #default="scope">
            <div class="flex-center" :style="{ color: eventTypeStyle(scope.row.eventType) }">
              <span class="point mg-r-8" :style="{ background: eventTypeStyle(scope.row.eventType) }" />
              <span>{{ formatEventType(scope.row.eventType) }}</span>
            </div>
          </template>
        </px-table-column>
        <px-table-column label="操作" width="150" fixed="right" align="center">
          <template #default="scope">
            <px-tooltip content="详情" placement="top">
              <px-button link icon="Tickets" type="primary" @click="handleDetail(scope.row)" />
            </px-tooltip>
            <px-tooltip content="处理" placement="top">
              <px-button link icon="ChevronRightCircle" type="primary" @click="handleResolve(scope.row)" />
            </px-tooltip>
            <px-tooltip content="删除" placement="top">
              <px-button link icon="Delete" type="danger" @click="handleDelete(scope.row)" />
            </px-tooltip>
          </template>
        </px-table-column>
      </px-table>
      <pagination
        v-show="total > 0"
        v-model:page="pageNum"
        v-model:limit="pageSize"
        class="table-pagination"
        :total="total"
        @pagination="handleQuery"
      />
    </div>
    <div v-if="resolveVisible">
      <Resolve v-model:visible="resolveVisible" :handleType="handleType" :rowData="rowData" @refresh="refresh" />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted } from "vue";
import CustomTabs from "@/components/Tabs/index.vue";
import { queryDictData } from "@/api/common";
import { getListAPI, deleteListDataAPI } from "@/api/energy/monitor";
import { PxMessage, PxMessageBox } from "px-ui";
import Resolve from "@/views/common/energy/monitor/monitorEvent/component/resolve.vue";
import { formatPeriod, formatAlarm, formatEventType, eventTypeStyle } from "@/views/common/energy/monitor/monitorEvent/utils";

import { useRouter } from "vue-router";

const router = useRouter();

const formRef = ref();

const state = reactive({
  monitorType: "",
  queryParams: {
    cycle: "",
    energy: "",
    date: ""
  },
  cycleList: [
    {
      value: "D",
      name: "每日"
    },
    {
      value: "M",
      name: "每月"
    }
  ],
  energyList: [],
  tableLoading: false,
  tableData: [],
  rowData: {},
  total: 10,
  pageNum: 1,
  pageSize: 20,
  resolveVisible: false,
  handleType: "Resolve"
});
const { monitorType, queryParams, cycleList, energyList, tableLoading, tableData, rowData, total, pageNum, pageSize, resolveVisible, handleType } =
  toRefs(state);

const tabList = ref([
  { name: "", label: "全部" },
  { name: "N", label: "待处理" },
  { name: "H", label: "处理中" },
  { name: "C", label: "已完成" }
]);
const activeName = ref("");

const monitorTypeList = ref([
  { value: "", name: "All" },
  { value: "consume", name: "能耗监控" },
  { value: "load", name: "负荷监控" },
  { value: "loss", name: "损耗监控" }
]);

// 切换tab
const handelTabSelected = val => {
  activeName.value = val;
  handleQuery();
};

const changeMonitorType = type => {
  state.monitorType = type;
  handleQuery();
};

onMounted(() => {
  // 双碳页面跳转带id过来
  if (router.currentRoute.value.query.id) {
    state.handleType = "Detail";
    state.resolveVisible = true;
  }
  getEnergySelect();
  handleQuery();
});

// 获取能源下拉框数据
const getEnergySelect = async () => {
  const energyList = await queryDictData({ typeCode: "ENERGY" });
  state.energyList = [...energyList];
};

// 查询
const handleQuery = async () => {
  try {
    state.tableLoading = true;
    const { cycle, energy, date } = state.queryParams;
    const params = {
      pageNum: state.pageNum,
      pageSize: state.pageSize,
      alarmLevel: "",
      kind: activeName.value === "" ? null : activeName.value,
      period: cycle === "" ? null : cycle,
      alarmTimeStart: date === "" ? "" : date[0],
      alarmTimeEnd: date === "" ? "" : date[1],
      energyType: energy === "" ? null : energy,
      monitorType: state.monitorType
    };
    const res = await getListAPI(params);
    state.total = res.total;
    state.tableData = res.data;
  } catch (err) {
    console.log(err);
  } finally {
    state.tableLoading = false;
  }
};

// 重置
const resetQuery = () => {
  formRef.value.resetFields();
  handleQuery();
};

// 详情
const handleDetail = row => {
  state.handleType = "Detail";
  state.rowData = row;
  state.resolveVisible = true;
};

// 处理
const handleResolve = row => {
  state.handleType = "Resolve";
  state.rowData = row;
  state.resolveVisible = true;
};

// 删除
const handleDelete = row => {
  const params = {
    id: row.id
  };
  sureDelete(params);
};

const sureDelete = async params => {
  PxMessageBox.confirm("是否确认删除？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      const res = await deleteListDataAPI(params);
      if (res.length > 0) {
        PxMessage.error(res);
      } else {
        PxMessage.success("删除成功");
        handleQuery();
      }
    })
    .catch(() => {});
};

const refresh = () => {
  state.resolveVisible = false;
  handleQuery();
};
</script>

<style lang="scss" scoped>
@import url("@/views/common/energy/monitor/monitorEvent/scss/common.scss");

.monitor-tab {
  display: flex;
  align-items: center;
  justify-content: space-around;
  // width: 196px;
  height: 34px;
  padding: 0 4px;
  margin-right: 16px;
  margin-bottom: 16px;
  background: #f4f4f4;
  border-radius: 4px;

  .monitor-tab-item {
    height: 26px;
    padding: 0 8px;
    font-size: 14px;
    line-height: 26px;
    text-align: center;
    cursor: pointer;
  }

  .active-monitor-tab {
    color: #fff;
    background: #4089f7;
    border-radius: 4px;
    box-shadow: 0 2px 4px 0 #b5d2fe;
  }
}
</style>
